<template>

    <el-alert v-show="alertshow" 
    style="position: fixed;width: 30%;z-index: 999;left: 50%;top:40px;transform: translate(-50%,0);" 
    title="正在上传...." type="warning" show-icon />
    <div id="tempdownload">

        <el-form :model="form" label-width="auto" style="max-width: 600px">
            <el-form-item label="选择年份">
                <el-date-picker v-model="form.year" value-format="YYYY" type="year" placeholder="选择年份" />
            </el-form-item>
            <el-form-item label="导入Excel文件">
                <el-upload v-model:file-list="fileList" ref="uploadRef" class="upload-demo" action=""
                    :auto-upload="false">
                    <template #trigger>
                        <el-button type="primary">选择文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>

        </el-form>
        <el-button style="margin: 0 auto;" block type="success" @click="upload()" size="normal">导入</el-button>
        <div>
            <div>提示:</div>
            <div>1、如果本地没有EXCEL数据模板，请在这点击
                <span style="color: #0000ff;cursor: pointer;" @click="downtemp()">下载</span>EXCEL数据模板。
            </div>
            <div>2、待导入EXCEL文件数据格式请严格按照EXCEL数据模板格式进行整理。</div>
            <div>3、待导入EXCEL文件数据量若过大应分批导入,每次不超过5000条数据为最佳。</div>
        </div>
    </div>
</template>

<script setup>
import { onMounted } from "vue";
import { dataStore } from "../../store/data";
import { Download } from '@element-plus/icons-vue'
import FileSaver from "file-saver";
import * as XLSX from 'xlsx';
import $sys from "../../api/sys";
import $req from "../../api/request";
import { ElMessage } from "element-plus";
const alertshow = ref(false);
const fileList = ref([]);
const $store = dataStore();
const form = reactive({ year: '' });
const uploadRef = ref();
const reqString = ref('/population_data/getTemplate');
const tempname = ref('人口数据模板');
onMounted(() => {
    getYear();
    if ($store.download == 'pop') {
        reqString.value = '/population_data/getTemplate';
        tempname.value = '人口数据导入模板';
    } else if ($store.download == 'GDP') {
        reqString.value = '/gdp/getTemplate';
        tempname.value = 'GDP导入模板';
    }
});
const yearlist = ref([]);
function getYear() {
    const currentYear = new Date().getFullYear();
    const startYear = currentYear - 10;
    const endYear = currentYear + 5;
    for (let i = startYear; i < currentYear; i++) {
        yearlist.value.push(i);
    }
    for (let i = currentYear; i <= endYear; i++) {
        yearlist.value.push(i);
    }
}
function upload() {
    if (form.year == '') {
        ElMessage({
            message: '请选择年份!',
            type: 'warning'
        })
    } else if (fileList.value.length == 0) {
        ElMessage({
            message: '请选择文件!',
            type: 'warning'
        })
    } else {
        alertshow.value = true;
        if ($store.download == 'workman') {
            WorkManup();
        } else if ($store.download == 'pop') {
            PoPup();
        } else if ($store.download == 'GDP') {
            GDPup()
        }
    }

}
function WorkManup() {
    const formData = new FormData();
    formData.append('year', form.year)
    fileList.value.forEach((item, index) => {
        formData.append('file', item.raw)
    })
    $sys.upWorkManFile(formData).then(res => {
        if (res.code == 200) {
            alertshow.value = false;
            ElMessage({
                message: '操作成功!',
                type: 'success'
            })
        }
    })
}
function PoPup() {
    const formData = new FormData();
    formData.append('year', form.year)
    fileList.value.forEach((item, index) => {
        formData.append('file', item.raw)
    })
    $sys.uppopFile(formData).then(res => {

        if (res.code == 200) {
            alertshow.value = false;
            ElMessage({
                message: '操作成功!',
                type: 'success'
            })
        }
    })
}
function GDPup() {
    const formData = new FormData();
    formData.append('year', form.year)
    fileList.value.forEach((item, index) => {
        formData.append('file', item.raw)
    })
    $sys.upGDPFile(formData).then(res => {
        if (res.code == 200) {
            alertshow.value = false;
            ElMessage({
                message: '操作成功!',
                type: 'success'
            })
        }
    })
}
function downtemp() {
    $req({
        url: reqString.value,
        method: 'get',
        responseType: 'blob'
    }).then(res => {
        let name = tempname.value;
        exexcel(res, name);
    })
}
function exexcel(res, name) {
    let blob = new Blob([res], {
        type: 'application/vnd.ms-excel',
    });
    let fileName = name + ".xlsx";
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
    } else {
        var link = document.createElement("a");//定义一个a标签
        link.href = window.URL.createObjectURL(blob);//需要生成一个 URL 来实现下载，链接到blob上
        link.download = fileName;//下载后的文件名称
        // console.log("fileName", link);
        link.click(); //模拟在按钮上实现一次鼠标点击
        window.URL.revokeObjectURL(link.href); //释放 URL 对象
    }
}
</script>

<style scoped>
#tempdownload {
    padding: 30px;
}
.el-alert {
  margin: 20px 0 0;
}
.el-alert:first-child {
  margin: 0;
}
</style>
